package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dto.input.CasingCompareInputDto;
import com.b511.swpu.cementbackend.dto.input.SqlDto;
import com.b511.swpu.cementbackend.dto.input.WorkQueryDto;
import com.b511.swpu.cementbackend.dto.output.DataQueryOutputDto;
import com.b511.swpu.cementbackend.dto.output.WellBrowseOutDto;
import com.b511.swpu.cementbackend.dto.output.WellinfoDto;
import com.b511.swpu.cementbackend.entity.BA_Well;
import com.b511.swpu.cementbackend.entity.CM_WorkBaseInfo;
import com.b511.swpu.cementbackend.entity.SysUser;
import com.b511.swpu.cementbackend.repository.*;
import com.b511.swpu.cementbackend.service.DataQueryService;
import com.b511.swpu.cementbackend.util.DBHelper;
import com.b511.swpu.cementbackend.util.FileUtil;
import com.b511.swpu.cementbackend.util.R;
import com.b511.swpu.cementbackend.util.UnZipUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.*;

@Service
public class DataQueryServiceImpl implements DataQueryService {
    private final WellDocRepository wellDocRepository;

    private final CM_WorkBaseInfoRepository cm_workBaseInfoRepository;

    private final CompareTreeRepository compareTreeRepository;

    private final SysUserRepository sysUserRepository;

    private final SYSM_CompanyRepository sysm_companyRepository;

    private final BA_WellRepository ba_wellRepository;

    DBHelper dbHelper=new DBHelper();

    @Value("${doc.root}")
    private String doc_root;

    public DataQueryServiceImpl(WellDocRepository wellDocRepository, CM_WorkBaseInfoRepository cm_workBaseInfoRepository,
                                CompareTreeRepository compareTreeRepository, SysUserRepository sysUserRepository, SYSM_CompanyRepository sysm_companyRepository, BA_WellRepository ba_wellRepository) {
        this.wellDocRepository = wellDocRepository;
        this.cm_workBaseInfoRepository = cm_workBaseInfoRepository;
        this.compareTreeRepository = compareTreeRepository;
        this.sysUserRepository = sysUserRepository;
        this.sysm_companyRepository = sysm_companyRepository;
        this.ba_wellRepository = ba_wellRepository;
    }

    @Override
    public   R getWorkByCondition(WorkQueryDto workQueryDto, PageRequest pageRequest) throws Exception
    {
        System.out.println(workQueryDto.getArea()+":"+workQueryDto.getCountry());
        String json="[{ \"wellName\": 'WZ11-2-B1S1', \"casingSize\": '7',  \"cementType\": '尾管固井',  \"date\":'2019-3-3',  \"cementCompany\": '湛江作业公司',  \"welltype\": '直井', \"wellSpacing\":'生产井',  \"country\":'中国',   \"area\":'南海',  \"block\":'北部湾' }]";

        List<DataQueryOutputDto> dataQueryOutputDtoList = new ArrayList<>();

        DataQueryOutputDto dto = new DataQueryOutputDto();
        dto.setWellName("WZ11-2-B1S1");
        dto.setCasingSize("7");
        dto.setCementType("尾管固井");
        dto.setDate("2019-3-3");
        dto.setCementCompany("湛江作业公司");
        dto.setWelltype("直井");
        dto.setWellSpacing("生产井");
        dto.setCountry("中国");
        dto.setArea("南海");
        dto.setBlock("北部湾");
        dataQueryOutputDtoList.add(dto);

        return R.ok().putData(dataQueryOutputDtoList);

    }

    @Override
    public R filePreview(String filePath,HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin","*");
        System.out.println(filePath);
//        filePath=filePath.replaceAll("xiegang","//");
        try {
            filePath= URLDecoder.decode(filePath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        filePath=filePath.replaceAll("xiegang","//");
        System.out.println(filePath);
        File file =new File(filePath);
        if (file.exists()) {
//            byte[] data = null;
////            FileInputStream input=null;
////            try {
////                input= new FileInputStream(file);
////                data = new byte[input.available()];
////                input.read(data);
////
            byte[] data = null;
            FileInputStream input=null;
            try {
                input= new FileInputStream(file);
                data = new byte[1024];
                int readTemp=0;
                while ((readTemp=input.read(data))!=-1){
                    response.getOutputStream().write(data,0,readTemp);
                }
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            }finally{
                try {
                    if(input!=null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return R.ok();
    }

    @Override
    public R getWellFile(String wellName) {

        String static_root=doc_root+wellName;
        File file= new File(static_root);
        if (file.exists()){
            System.out.println(static_root);
            FileUtil dir =new FileUtil();
            String json=dir.scan(static_root)+"}";

            //做成树状json
            StringBuilder sb = new StringBuilder(json);
            sb.insert(0,"[");
            sb.insert(sb.length(),"]");
            json=sb.toString();
//        JSONObject  jsonObject = JSONObject.fromObject(json);
            JSONArray jsonArray=JSONArray.fromObject(json);
            return R.ok().putData(jsonArray);
        }else {
            return R.ok();
        }



    }

    // 通过井名查询返回该井的全部套管
    @Override
    public R getCasingsData(String wellName){
        return R.ok().putData(cm_workBaseInfoRepository.findByWellName(wellName));
    }

    /* 根据属性名获取属性值
     * */
    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            return null;
        }
    }

    // 通过井名获取当前井的全部套管信息
    @Override
    public R getWorkBaseInfo(String wellName){
        // key:value
        // 字段中文名:实体内英文字段
        Map<String, String> workBasicInfo = new HashMap<String, String>(){
            {
                // 作业基本信息
                put("井眼直径(in)","holeSize");
                put("实际井深(m)","holeDepth");
                put("套管外径(in)","casingSize");
                put("套管实际下深(m)","casingBtmDepth");
                put("设计水泥浆返高(m)","returnDepth1");
                put("管内水泥塞长度(m)","cementPlug");
                put("设计裸眼附加量(%)","additiveVolume1");
                put("实测水泥浆返高(m)","returnDepth2");
                put("实探水泥塞顶深(m)","PlugTopDepth");
                put("实际裸眼附加量(%)","additiveVolume2");
                put("固井方式","cementType");
                // 泥浆信息
                put("泥浆类型","mudType");
                put("泥浆密度(g/cm3)","mudType");
                put("漏斗粘度(秒/夸脱)","FV");
                put("屈服值(Pa)","PV");
                put("塑性粘度(Pa)","YP");
                put("切力(Pa)","CP");
                // 固井前循环参数
                put("循环排量(L/Min)","cycleDisplacement");
                put("循环泵压(Psi)","cyclePump");
                put("裸眼环空返速(m/s)","AV");

                // 施工配方和性能(三级目录项，此项暂时不展示)
                // 首浆配方和性能
                put("首浆水泥浆类型","sluryType1");
                put("首浆施工配方","fourmula1");
                put("首浆试验温度(℃)","BHSTCT1");
                put("首浆密度(g/cm3)","sluryDensity1");
                put("首浆造浆率(cuft/sk)","pulpingRate1");
                put("首浆混合水率(gal/sk)","mixedWaterRate1");
                put("首浆失水量(ml/7Mpa.30min)","lostWater1");
                put("首浆抗压强度(Psi)","compressiveStrength1");
                put("首浆可泵时间(hr:min)","pumpTime1");
                put("首浆稠化时间(hr:min)","thickeningTime1");
                // 中间液配方和性能
                put("中间液水泥浆类型","sluryType2");
                put("中间液施工配方","fourmula2");
                put("中间液试验温度(℃)","BHSTCT2");
                put("中间液密度(g/cm3)","sluryDensity2");
                put("中间液造浆率(cuft/sk)","pulpingRate2");
                put("中间液混合水率(gal/sk)","mixedWaterRate2");
                put("中间液失水量(ml/7Mpa.30min)","lostWater2");
                put("中间液抗压强度(Psi)","compressiveStrength2");
                put("中间液可泵时间(hr:min)","pumpTime2");
                put("中间液稠化时间(hr:min)","thickeningTime2");
                // 尾桨配方和性能
                put("尾浆水泥浆类型","sluryType3");
                put("尾浆施工配方","fourmula3");
                put("尾浆试验温度(℃)","BHSTCT3");
                put("尾浆密度(g/cm3)","sluryDensity3");
                put("尾浆造浆率(cuft/sk)","pulpingRate3");
                put("尾浆混合水率(gal/sk)","mixedWaterRate3");
                put("尾浆失水量(ml/7Mpa.30min)","lostWater3");
                put("尾浆抗压强度(Psi)","compressiveStrength3");
                put("尾浆可泵时间(hr:min)","pumpTime3");
                put("尾浆稠化时间(hr:min)","thickeningTime3");

                // 作业数据
                // 首浆作业数据
                put("首浆水泥浆体积(bbls)","sluryVol1");
                put("首浆干水泥用量(ton)","dryCementVol1");
                put("首浆混合水用量(bbls)","mixWaterVol1");
                put("首浆水泥浆最高密度(g/cm3)","sluryMaxDensity1");
                put("首浆水泥浆最低密度(g/cm3)","sluryMinDensity1");
                put("首浆水泥浆平均密度(g/cm3)","sluryAvgDensity1");
                put("首浆替浆量(bbl)","replaceVol1");
                put("首浆替浆速度(bbl/min)","replaceSpeed1");
                put("首浆碰压前最高顶替压力(MPa/Psi)","maxDisplacement1");
                put("首浆施工总耗时(min)","workTime1");
                put("首浆施工人员","workMan1");
                put("首浆施工日期","workDate1");
                // 中间液作业数据
                put("中间液水泥浆体积(bbls)","sluryVol2");
                put("中间液干水泥用量(ton)","dryCementVol2");
                put("中间液混合水用量(bbls)","mixWaterVol2");
                put("中间液水泥浆最高密度(g/cm3)","sluryMaxDensity2");
                put("中间液水泥浆最低密度(g/cm3)","sluryMinDensity2");
                put("中间液水泥浆平均密度(g/cm3)","sluryAvgDensity2");
                put("中间液替浆量(bbl)","replaceVol2");
                put("中间液替浆速度(bbl/min)","replaceSpeed2");
                put("中间液碰压前最高顶替压力(MPa/Psi)","maxDisplacement2");
                put("中间液施工总耗时(min)","workTime2");
                put("中间液施工人员","workMan2");
                put("中间液施工日期","workDate2");
                // 尾桨作业数据
                put("尾桨水泥浆体积(bbls)","sluryVol3");
                put("尾桨干水泥用量(ton)","dryCementVol3");
                put("尾桨混合水用量(bbls)","mixWaterVol3");
                put("尾桨水泥浆最高密度(g/cm3)","sluryMaxDensity3");
                put("尾桨水泥浆最低密度(g/cm3)","sluryMinDensity3");
                put("尾桨水泥浆平均密度(g/cm3)","sluryAvgDensity3");
                put("尾桨替浆量(bbl)","replaceVol3");
                put("尾桨替浆速度(bbl/min)","replaceSpeed3");
                put("尾桨碰压前最高顶替压力(MPa/Psi)","maxDisplacement3");
                put("尾桨施工总耗时(min)","workTime3");
                put("尾桨施工人员","workMan3");
                put("尾桨施工日期","workDate3");
                // 前置液
                // 清洗液
                put("清洗液组成及性能","cleaningFluidFormula");
                put("清洗液密度(g/cm3)","cleaningFluidDensity");
                put("清洗液用量(bbl)","cleaningFluidVol");
                // 隔离液
                put("隔离液组成及性能","spacerFluidFormula");
                put("隔离液密度(g/cm3)","spacerFluidDensity");
                put("隔离液用量(bbl)","spacerFluidVol");

            }
        };

        // title1 作业基本信息
        String title1 = "作业基本信息";
        List<String> typeList1 = new ArrayList<>();
        typeList1.add("井眼直径(in)");
        typeList1.add("实际井深(m)");
        typeList1.add("套管外径(in)");
        typeList1.add("套管实际下深(m)");
        typeList1.add("设计水泥浆返高(m)");
        typeList1.add("管内水泥塞长度(m)");
        typeList1.add("设计裸眼附加量(%)");
        typeList1.add("实测水泥浆返高(m)");
        typeList1.add("实探水泥塞顶深(m)");
        typeList1.add("实际裸眼附加量(%)");
        typeList1.add("固井方式");

        String jsonStr = "";

        // 通过查询获得套管信息(此处模拟数据)
        List<CM_WorkBaseInfo> baseInfoList = cm_workBaseInfoRepository.findByWellName(wellName);
        if (0 == baseInfoList.size()){
            return R.ok().putData("");
        }
        // TODO:构造表头
        String tableHead = "";
        tableHead += "[";
        tableHead += "\"套管尺寸\"";
        for (CM_WorkBaseInfo workBaseInfo : baseInfoList){
            tableHead += ",";
            tableHead += "\"" + workBaseInfo.getCasingSize() +"\"";
        }
        tableHead += "]";

        // TODO:构造表数据JSON
        jsonStr += "[";

        for(String type : typeList1){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title1 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList1.indexOf(type) < typeList1.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }


        // title2 泥浆信息
        String title2 = "泥浆信息";
        List<String> typeList2 = new ArrayList<>();
        typeList2.add("泥浆类型");
        typeList2.add("泥浆密度(g/cm3)");
        typeList2.add("漏斗粘度(秒/夸脱)");
        typeList2.add("屈服值(Pa)");
        typeList2.add("塑性粘度(Pa)");
        typeList2.add("切力(Pa)");

        jsonStr += ",";
        for(String type : typeList2){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title2 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList2.indexOf(type) < typeList2.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title3 固井前循环参数
        String title3 = "固井前循环参数";
        List<String> typeList3 = new ArrayList<>();
        typeList3.add("循环排量(L/Min)");
        typeList3.add("循环泵压(Psi)");
        typeList3.add("裸眼环空返速(m/s)");

        jsonStr += ",";
        for(String type : typeList3){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title3 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList3.indexOf(type) < typeList3.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title4 首浆配方和性能
        String title4 = "首浆配方和性能";
        List<String> typeList4 = new ArrayList<>();
        typeList4.add("首浆水泥浆类型");
        typeList4.add("首浆施工配方");
        typeList4.add("首浆试验温度(℃)");
        typeList4.add("首浆密度(g/cm3)");
        typeList4.add("首浆造浆率(cuft/sk)");
        typeList4.add("首浆混合水率(gal/sk)");
        typeList4.add("首浆失水量(ml/7Mpa.30min)");
        typeList4.add("首浆抗压强度(Psi)");
        typeList4.add("首浆可泵时间(hr:min)");
        typeList4.add("首浆稠化时间(hr:min)");

        jsonStr += ",";
        for(String type : typeList4){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title4 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList4.indexOf(type) < typeList4.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title5 中间液配方和性能
        String title5 = "中间液配方和性能";
        List<String> typeList5 = new ArrayList<>();
        typeList5.add("中间液水泥浆类型");
        typeList5.add("中间液施工配方");
        typeList5.add("中间液试验温度(℃)");
        typeList5.add("中间液密度(g/cm3)");
        typeList5.add("中间液造浆率(cuft/sk)");
        typeList5.add("中间液混合水率(gal/sk)");
        typeList5.add("中间液失水量(ml/7Mpa.30min)");
        typeList5.add("中间液抗压强度(Psi)");
        typeList5.add("中间液可泵时间(hr:min)");
        typeList5.add("中间液稠化时间(hr:min)");

        jsonStr += ",";
        for(String type : typeList5){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title5 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList5.indexOf(type) < typeList5.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title6 尾浆配方和性能
        String title6 = "尾浆配方和性能";
        List<String> typeList6 = new ArrayList<>();
        typeList6.add("尾浆水泥浆类型");
        typeList6.add("尾浆施工配方");
        typeList6.add("尾浆试验温度(℃)");
        typeList6.add("尾浆密度(g/cm3)");
        typeList6.add("尾浆造浆率(cuft/sk)");
        typeList6.add("尾浆混合水率(gal/sk)");
        typeList6.add("尾浆失水量(ml/7Mpa.30min)");
        typeList6.add("尾浆抗压强度(Psi)");
        typeList6.add("尾浆可泵时间(hr:min)");
        typeList6.add("尾浆稠化时间(hr:min)");

        jsonStr += ",";
        for(String type : typeList6){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title6 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList6.indexOf(type) < typeList6.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title7 首浆作业数据
        String title7 = "首浆作业数据";
        List<String> typeList7 = new ArrayList<>();
        typeList7.add("首浆水泥浆体积(bbls)");
        typeList7.add("首浆干水泥用量(ton)");
        typeList7.add("首浆混合水用量(bbls)");
        typeList7.add("首浆水泥浆最高密度(g/cm3)");
        typeList7.add("首浆水泥浆最低密度(g/cm3)");
        typeList7.add("首浆水泥浆平均密度(g/cm3)");
        typeList7.add("首浆替浆量(bbl)");
        typeList7.add("首浆替浆速度(bbl/min)");
        typeList7.add("首浆碰压前最高顶替压力(MPa/Psi)");
        typeList7.add("首浆施工总耗时(min)");
        typeList7.add("首浆施工人员");
        typeList7.add("首浆施工日期");

        jsonStr += ",";
        for(String type : typeList7){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title7 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList7.indexOf(type) < typeList7.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title8 中间液作业数据
        String title8 = "中间液作业数据";
        List<String> typeList8 = new ArrayList<>();
        typeList8.add("中间液水泥浆体积(bbls)");
        typeList8.add("中间液干水泥用量(ton)");
        typeList8.add("中间液混合水用量(bbls)");
        typeList8.add("中间液水泥浆最高密度(g/cm3)");
        typeList8.add("中间液水泥浆最低密度(g/cm3)");
        typeList8.add("中间液水泥浆平均密度(g/cm3)");
        typeList8.add("中间液替浆量(bbl)");
        typeList8.add("中间液替浆速度(bbl/min)");
        typeList8.add("中间液碰压前最高顶替压力(MPa/Psi)");
        typeList8.add("中间液施工总耗时(min)");
        typeList8.add("中间液施工人员");
        typeList8.add("中间液施工日期");

        jsonStr += ",";
        for(String type : typeList8){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title8 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList8.indexOf(type) < typeList8.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title9 尾浆作业数据
        String title9 = "尾浆作业数据";
        List<String> typeList9 = new ArrayList<>();
        typeList9.add("尾浆水泥浆体积(bbls)");
        typeList9.add("尾浆干水泥用量(ton)");
        typeList9.add("尾浆混合水用量(bbls)");
        typeList9.add("尾浆水泥浆最高密度(g/cm3)");
        typeList9.add("尾浆水泥浆最低密度(g/cm3)");
        typeList9.add("尾浆水泥浆平均密度(g/cm3)");
        typeList9.add("尾浆替浆量(bbl)");
        typeList9.add("尾浆替浆速度(bbl/min)");
        typeList9.add("尾浆碰压前最高顶替压力(MPa/Psi)");
        typeList9.add("尾浆施工总耗时(min)");
        typeList9.add("尾浆施工人员");
        typeList9.add("尾浆施工日期");

        jsonStr += ",";
        for(String type : typeList9){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title9 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList9.indexOf(type) < typeList9.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title10 清洗液
        String title10 = "清洗液数据";
        List<String> typeList10 = new ArrayList<>();
        typeList10.add("清洗液组成及性能");
        typeList10.add("清洗液密度(g/cm3)");
        typeList10.add("清洗液用量(bbl)");

        jsonStr += ",";
        for(String type : typeList10){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title10 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList10.indexOf(type) < typeList10.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title11 隔离液
        String title11 = "隔离液数据";
        List<String> typeList11 = new ArrayList<>();
        typeList11.add("隔离液组成及性能");
        typeList11.add("隔离液密度(g/cm3)");
        typeList11.add("隔离液用量(bbl)");

        jsonStr += ",";
        for(String type : typeList11){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title11 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getCasingSize() + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList11.indexOf(type) < typeList11.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // [ 配对 ]
        jsonStr += "]";


        JSONObject jsonobj = new JSONObject();
        JSONArray jarr = JSONArray.fromObject(jsonStr);
        JSONArray head = JSONArray.fromObject(tableHead);
        jsonobj.put("tableHead", head);
        jsonobj.put("list",jarr);
        return R.ok().putData(jsonobj);
    }

    // 套管对比
    @Override
    public R getCasingCompare(CasingCompareInputDto compareInDto){
        // key:value
        // 字段中文名:实体内英文字段
        Map<String, String> workBasicInfo = new HashMap<String, String>(){
            {
                // 作业基本信息
                put("井眼直径(in)","holeSize");
                put("实际井深(m)","holeDepth");
                put("套管外径(in)","casingSize");
                put("套管实际下深(m)","casingBtmDepth");
                put("设计水泥浆返高(m)","returnDepth1");
                put("管内水泥塞长度(m)","cementPlug");
                put("设计裸眼附加量(%)","additiveVolume1");
                put("实测水泥浆返高(m)","returnDepth2");
                put("实探水泥塞顶深(m)","PlugTopDepth");
                put("实际裸眼附加量(%)","additiveVolume2");
                put("固井方式","cementType");
                // 泥浆信息
                put("泥浆类型","mudType");
                put("泥浆密度(g/cm3)","mudType");
                put("漏斗粘度(秒/夸脱)","FV");
                put("屈服值(Pa)","PV");
                put("塑性粘度(Pa)","YP");
                put("切力(Pa)","CP");
                // 固井前循环参数
                put("循环排量(L/Min)","cycleDisplacement");
                put("循环泵压(Psi)","cyclePump");
                put("裸眼环空返速(m/s)","AV");

                // 施工配方和性能(三级目录项，此项暂时不展示)
                // 首浆配方和性能
                put("首浆水泥浆类型","sluryType1");
                put("首浆施工配方","fourmula1");
                put("首浆试验温度(℃)","BHSTCT1");
                put("首浆密度(g/cm3)","sluryDensity1");
                put("首浆造浆率(cuft/sk)","pulpingRate1");
                put("首浆混合水率(gal/sk)","mixedWaterRate1");
                put("首浆失水量(ml/7Mpa.30min)","lostWater1");
                put("首浆抗压强度(Psi)","compressiveStrength1");
                put("首浆可泵时间(hr:min)","pumpTime1");
                put("首浆稠化时间(hr:min)","thickeningTime1");
                // 中间液配方和性能
                put("中间液水泥浆类型","sluryType2");
                put("中间液施工配方","fourmula2");
                put("中间液试验温度(℃)","BHSTCT2");
                put("中间液密度(g/cm3)","sluryDensity2");
                put("中间液造浆率(cuft/sk)","pulpingRate2");
                put("中间液混合水率(gal/sk)","mixedWaterRate2");
                put("中间液失水量(ml/7Mpa.30min)","lostWater2");
                put("中间液抗压强度(Psi)","compressiveStrength2");
                put("中间液可泵时间(hr:min)","pumpTime2");
                put("中间液稠化时间(hr:min)","thickeningTime2");
                // 尾桨配方和性能
                put("尾浆水泥浆类型","sluryType3");
                put("尾浆施工配方","fourmula3");
                put("尾浆试验温度(℃)","BHSTCT3");
                put("尾浆密度(g/cm3)","sluryDensity3");
                put("尾浆造浆率(cuft/sk)","pulpingRate3");
                put("尾浆混合水率(gal/sk)","mixedWaterRate3");
                put("尾浆失水量(ml/7Mpa.30min)","lostWater3");
                put("尾浆抗压强度(Psi)","compressiveStrength3");
                put("尾浆可泵时间(hr:min)","pumpTime3");
                put("尾浆稠化时间(hr:min)","thickeningTime3");

                // 作业数据
                // 首浆作业数据
                put("首浆水泥浆体积(bbls)","sluryVol1");
                put("首浆干水泥用量(ton)","dryCementVol1");
                put("首浆混合水用量(bbls)","mixWaterVol1");
                put("首浆水泥浆最高密度(g/cm3)","sluryMaxDensity1");
                put("首浆水泥浆最低密度(g/cm3)","sluryMinDensity1");
                put("首浆水泥浆平均密度(g/cm3)","sluryAvgDensity1");
                put("首浆替浆量(bbl)","replaceVol1");
                put("首浆替浆速度(bbl/min)","replaceSpeed1");
                put("首浆碰压前最高顶替压力(MPa/Psi)","maxDisplacement1");
                put("首浆施工总耗时(min)","workTime1");
                put("首浆施工人员","workMan1");
                put("首浆施工日期","workDate1");
                // 中间液作业数据
                put("中间液水泥浆体积(bbls)","sluryVol2");
                put("中间液干水泥用量(ton)","dryCementVol2");
                put("中间液混合水用量(bbls)","mixWaterVol2");
                put("中间液水泥浆最高密度(g/cm3)","sluryMaxDensity2");
                put("中间液水泥浆最低密度(g/cm3)","sluryMinDensity2");
                put("中间液水泥浆平均密度(g/cm3)","sluryAvgDensity2");
                put("中间液替浆量(bbl)","replaceVol2");
                put("中间液替浆速度(bbl/min)","replaceSpeed2");
                put("中间液碰压前最高顶替压力(MPa/Psi)","maxDisplacement2");
                put("中间液施工总耗时(min)","workTime2");
                put("中间液施工人员","workMan2");
                put("中间液施工日期","workDate2");
                // 尾桨作业数据
                put("尾桨水泥浆体积(bbls)","sluryVol3");
                put("尾桨干水泥用量(ton)","dryCementVol3");
                put("尾桨混合水用量(bbls)","mixWaterVol3");
                put("尾桨水泥浆最高密度(g/cm3)","sluryMaxDensity3");
                put("尾桨水泥浆最低密度(g/cm3)","sluryMinDensity3");
                put("尾桨水泥浆平均密度(g/cm3)","sluryAvgDensity3");
                put("尾桨替浆量(bbl)","replaceVol3");
                put("尾桨替浆速度(bbl/min)","replaceSpeed3");
                put("尾桨碰压前最高顶替压力(MPa/Psi)","maxDisplacement3");
                put("尾桨施工总耗时(min)","workTime3");
                put("尾桨施工人员","workMan3");
                put("尾桨施工日期","workDate3");
                // 前置液
                // 清洗液
                put("清洗液组成及性能","cleaningFluidFormula");
                put("清洗液密度(g/cm3)","cleaningFluidDensity");
                put("清洗液用量(bbl)","cleaningFluidVol");
                // 隔离液
                put("隔离液组成及性能","spacerFluidFormula");
                put("隔离液密度(g/cm3)","spacerFluidDensity");
                put("隔离液用量(bbl)","spacerFluidVol");

            }
        };

        // title1 作业基本信息
        String title1 = "作业基本信息";
        List<String> typeList1 = new ArrayList<>();
        typeList1.add("井眼直径(in)");
        typeList1.add("实际井深(m)");
        typeList1.add("套管外径(in)");
        typeList1.add("套管实际下深(m)");
        typeList1.add("设计水泥浆返高(m)");
        typeList1.add("管内水泥塞长度(m)");
        typeList1.add("设计裸眼附加量(%)");
        typeList1.add("实测水泥浆返高(m)");
        typeList1.add("实探水泥塞顶深(m)");
        typeList1.add("实际裸眼附加量(%)");
        typeList1.add("固井方式");

        String jsonStr = "";

        // 通过查询获得套管信息(此处模拟数据)
        List<CM_WorkBaseInfo> baseInfoList = new ArrayList<>();
        for (String id:compareInDto.getList()){
            System.out.println(id);
            CM_WorkBaseInfo tmp = cm_workBaseInfoRepository.findwellInfoDetailById(id);
            baseInfoList.add(tmp);
        }

        if (0 == baseInfoList.size()){
            return R.ok().putData("");
        }
        // TODO:构造井名表头
        String well = "";
        well += "[";
        well += "\"井名\"";
        for (CM_WorkBaseInfo workBaseInfo : baseInfoList){
            well += ",";
            well += "\"" + workBaseInfo.getWellName() +"\"";
        }
        well += "]";

        // TODO:构造表头
        String tableHead = "";
        tableHead += "[";
        tableHead += "\"套管尺寸\"";
        for (CM_WorkBaseInfo workBaseInfo : baseInfoList){
            tableHead += ",";
            tableHead += "\"" + workBaseInfo.getCasingSize() +"\"";
        }
        tableHead += "]";

        // TODO:构造表数据JSON
        jsonStr += "[";

        for(String type : typeList1){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title1 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList1.indexOf(type) < typeList1.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }


        // title2 泥浆信息
        String title2 = "泥浆信息";
        List<String> typeList2 = new ArrayList<>();
        typeList2.add("泥浆类型");
        typeList2.add("泥浆密度(g/cm3)");
        typeList2.add("漏斗粘度(秒/夸脱)");
        typeList2.add("屈服值(Pa)");
        typeList2.add("塑性粘度(Pa)");
        typeList2.add("切力(Pa)");

        jsonStr += ",";
        for(String type : typeList2){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title2 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList2.indexOf(type) < typeList2.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title3 固井前循环参数
        String title3 = "固井前循环参数";
        List<String> typeList3 = new ArrayList<>();
        typeList3.add("循环排量(L/Min)");
        typeList3.add("循环泵压(Psi)");
        typeList3.add("裸眼环空返速(m/s)");

        jsonStr += ",";
        for(String type : typeList3){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title3 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList3.indexOf(type) < typeList3.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title4 首浆配方和性能
        String title4 = "首浆配方和性能";
        List<String> typeList4 = new ArrayList<>();
        typeList4.add("首浆水泥浆类型");
        typeList4.add("首浆施工配方");
        typeList4.add("首浆试验温度(℃)");
        typeList4.add("首浆密度(g/cm3)");
        typeList4.add("首浆造浆率(cuft/sk)");
        typeList4.add("首浆混合水率(gal/sk)");
        typeList4.add("首浆失水量(ml/7Mpa.30min)");
        typeList4.add("首浆抗压强度(Psi)");
        typeList4.add("首浆可泵时间(hr:min)");
        typeList4.add("首浆稠化时间(hr:min)");

        jsonStr += ",";
        for(String type : typeList4){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title4 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList4.indexOf(type) < typeList4.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title5 中间液配方和性能
        String title5 = "中间液配方和性能";
        List<String> typeList5 = new ArrayList<>();
        typeList5.add("中间液水泥浆类型");
        typeList5.add("中间液施工配方");
        typeList5.add("中间液试验温度(℃)");
        typeList5.add("中间液密度(g/cm3)");
        typeList5.add("中间液造浆率(cuft/sk)");
        typeList5.add("中间液混合水率(gal/sk)");
        typeList5.add("中间液失水量(ml/7Mpa.30min)");
        typeList5.add("中间液抗压强度(Psi)");
        typeList5.add("中间液可泵时间(hr:min)");
        typeList5.add("中间液稠化时间(hr:min)");

        jsonStr += ",";
        for(String type : typeList5){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title5 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList5.indexOf(type) < typeList5.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title6 尾浆配方和性能
        String title6 = "尾浆配方和性能";
        List<String> typeList6 = new ArrayList<>();
        typeList6.add("尾浆水泥浆类型");
        typeList6.add("尾浆施工配方");
        typeList6.add("尾浆试验温度(℃)");
        typeList6.add("尾浆密度(g/cm3)");
        typeList6.add("尾浆造浆率(cuft/sk)");
        typeList6.add("尾浆混合水率(gal/sk)");
        typeList6.add("尾浆失水量(ml/7Mpa.30min)");
        typeList6.add("尾浆抗压强度(Psi)");
        typeList6.add("尾浆可泵时间(hr:min)");
        typeList6.add("尾浆稠化时间(hr:min)");

        jsonStr += ",";
        for(String type : typeList6){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title6 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList6.indexOf(type) < typeList6.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title7 首浆作业数据
        String title7 = "首浆作业数据";
        List<String> typeList7 = new ArrayList<>();
        typeList7.add("首浆水泥浆体积(bbls)");
        typeList7.add("首浆干水泥用量(ton)");
        typeList7.add("首浆混合水用量(bbls)");
        typeList7.add("首浆水泥浆最高密度(g/cm3)");
        typeList7.add("首浆水泥浆最低密度(g/cm3)");
        typeList7.add("首浆水泥浆平均密度(g/cm3)");
        typeList7.add("首浆替浆量(bbl)");
        typeList7.add("首浆替浆速度(bbl/min)");
        typeList7.add("首浆碰压前最高顶替压力(MPa/Psi)");
        typeList7.add("首浆施工总耗时(min)");
        typeList7.add("首浆施工人员");
        typeList7.add("首浆施工日期");

        jsonStr += ",";
        for(String type : typeList7){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title7 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList7.indexOf(type) < typeList7.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title8 中间液作业数据
        String title8 = "中间液作业数据";
        List<String> typeList8 = new ArrayList<>();
        typeList8.add("中间液水泥浆体积(bbls)");
        typeList8.add("中间液干水泥用量(ton)");
        typeList8.add("中间液混合水用量(bbls)");
        typeList8.add("中间液水泥浆最高密度(g/cm3)");
        typeList8.add("中间液水泥浆最低密度(g/cm3)");
        typeList8.add("中间液水泥浆平均密度(g/cm3)");
        typeList8.add("中间液替浆量(bbl)");
        typeList8.add("中间液替浆速度(bbl/min)");
        typeList8.add("中间液碰压前最高顶替压力(MPa/Psi)");
        typeList8.add("中间液施工总耗时(min)");
        typeList8.add("中间液施工人员");
        typeList8.add("中间液施工日期");

        jsonStr += ",";
        for(String type : typeList8){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title8 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList8.indexOf(type) < typeList8.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title9 尾浆作业数据
        String title9 = "尾浆作业数据";
        List<String> typeList9 = new ArrayList<>();
        typeList9.add("尾浆水泥浆体积(bbls)");
        typeList9.add("尾浆干水泥用量(ton)");
        typeList9.add("尾浆混合水用量(bbls)");
        typeList9.add("尾浆水泥浆最高密度(g/cm3)");
        typeList9.add("尾浆水泥浆最低密度(g/cm3)");
        typeList9.add("尾浆水泥浆平均密度(g/cm3)");
        typeList9.add("尾浆替浆量(bbl)");
        typeList9.add("尾浆替浆速度(bbl/min)");
        typeList9.add("尾浆碰压前最高顶替压力(MPa/Psi)");
        typeList9.add("尾浆施工总耗时(min)");
        typeList9.add("尾浆施工人员");
        typeList9.add("尾浆施工日期");

        jsonStr += ",";
        for(String type : typeList9){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title9 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList9.indexOf(type) < typeList9.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title10 清洗液
        String title10 = "清洗液数据";
        List<String> typeList10 = new ArrayList<>();
        typeList10.add("清洗液组成及性能");
        typeList10.add("清洗液密度(g/cm3)");
        typeList10.add("清洗液用量(bbl)");

        jsonStr += ",";
        for(String type : typeList10){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title10 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList10.indexOf(type) < typeList10.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // title11 隔离液
        String title11 = "隔离液数据";
        List<String> typeList11 = new ArrayList<>();
        typeList11.add("隔离液组成及性能");
        typeList11.add("隔离液密度(g/cm3)");
        typeList11.add("隔离液用量(bbl)");

        jsonStr += ",";
        for(String type : typeList11){
            jsonStr += "{";
            jsonStr += "\"name\":" + "\"" + title11 + "\",";
            jsonStr += "\"type\":" + "\"" + type + "\"" ;

            // 遍历List
            for (CM_WorkBaseInfo tmpBase : baseInfoList){
                Object value = getFieldValueByName(workBasicInfo.get(type), tmpBase);
                if (value!=null){
                    jsonStr += ",";
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + value.toString().replaceAll("\"","'") + "\"";
                }else {
                    jsonStr += ",";
                    // 空值
                    jsonStr += "\"" + tmpBase.getWellName() + "（" +  tmpBase.getCasingSize() + "）" + "\"" + ":" + "\"" + "\"";
                }
            }
            // 结尾格式
            if(typeList11.indexOf(type) < typeList11.size()-1 ){
                jsonStr += "},";
            }else {
                jsonStr += "}";
            }
        }

        // [ 配对 ]
        jsonStr += "]";

        JSONObject jsonobj = new JSONObject();
        JSONArray jarr = JSONArray.fromObject(jsonStr);
        JSONArray head = JSONArray.fromObject(tableHead);
        jsonobj.put("wells", well);
        jsonobj.put("tableHead", head);
        jsonobj.put("list",jarr);

        return R.ok().putData(jsonobj);
    }

//    @Override
//    public R wellBrowse(HttpServletRequest request) {
//        ////这个接口复杂度太高，不再使用，只供参考
//
//        //获取当前登陆人的公司
//        String token=request.getHeader("Authorization");
//        SysUser user = sysUserRepository.findByToken(token);
//        String loginUser_company=user.getCompany().getNAME();
//        List<String> list_company=sysm_companyRepository.findName();
//        //构造所有公司json
//        String data2="";
//        data2+="[";
//        for(String company:list_company){
//            data2+="{";
//            data2+="\"company\":" + "\"" + company + "\"";
//            data2+="},";
//        }
//        data2+="]";
//        JSONArray data2Json=JSONArray.fromObject(data2);
//
//        List<String> countrys=ba_wellRepository.findCountry(loginUser_company);
//        List<WellBrowseOutDto> out1s=new LinkedList<>();
//        for(String country:countrys){//只是country不同
//            WellBrowseOutDto out1=new WellBrowseOutDto();
//            out1.setLabel(country);
//            List<String> areas = null;
//            areas=ba_wellRepository.findArea(loginUser_company,country);
//            List<WellBrowseOutDto> out2s=new LinkedList<>();
//            for(String area:areas) {//只是area不用
//                WellBrowseOutDto out2=new WellBrowseOutDto();
//                out2.setLabel(area);
//                List<String> blocks = null;
//                blocks=ba_wellRepository.findBlock(loginUser_company,country,area);
//                List<WellBrowseOutDto> out3s=new LinkedList<>();
//                for(String block:blocks){//只是block不同
//                    WellBrowseOutDto out3=new WellBrowseOutDto();
//                    out3.setLabel(block);
//                    List<String> oilfields = null;
//                    oilfields=ba_wellRepository.findOilField(loginUser_company,country,area,block);
//                    List<WellBrowseOutDto> out4s=new LinkedList<>();
//                    for(String oilfield:oilfields) {//只是oilfield不用
//                        WellBrowseOutDto out4=new WellBrowseOutDto();
//                        out4.setLabel(oilfield);
//                        List<String> wellnames = null;
//                        wellnames=ba_wellRepository.findWellName(loginUser_company,country,area,block,oilfield);
//                        List<WellBrowseOutDto> out5s=new LinkedList<>();
//                        for(String wellname:wellnames) {//只是wellname不用
//                            WellBrowseOutDto out5=new WellBrowseOutDto();
//                            out5.setLabel(wellname);
//                            List<String> casingSizes = null;
//                            casingSizes=cm_workBaseInfoRepository.findCasingSize(loginUser_company,country,area,block,oilfield,wellname);
//                            List<WellBrowseOutDto> out6s=new LinkedList<>();
//                            for(String casingSize:casingSizes) {//只是wellname不用
//                                if(casingSize!=null){//上一步 数据库中casingSize为null
//                                    WellinfoDto it = cm_workBaseInfoRepository.findit(loginUser_company,country,area,block,oilfield,wellname, casingSize);
//                                    if(it.getCasingSize()!=null){
//                                        WellBrowseOutDto out6=new WellBrowseOutDto();
//                                        out6.setLabel(it.getCasingSize());
//                                        out6.setCM_WorkBaseInfo_ID(it.getCM_WorkBaseInfo_ID());
//                                        out6s.add(out6);
//                                    }
//                                }
//                            }
//                            out5.setChildren(out6s);
//                            out5s.add(out5);
//                        }
//                        out4.setChildren(out5s);
//                        out4s.add(out4);
//                    }
//                    out3.setChildren(out4s);
//                    out3s.add(out3);
//                }
//                out2.setChildren(out3s);
//                out2s.add(out2);
//            }
//            out1.setChildren(out2s);
//            out1s.add(out1);
//        }
//
//        return R.ok().put("data",out1s).put("data2",data2Json).put("data3",loginUser_company);
//    }

    @Override
    public R getCompareTree(){
        List<BA_Well> all = ba_wellRepository.findAll();
        Map<String,WellBrowseOutDto> dict=new HashMap<>();
        Set<WellBrowseOutDto> result = new HashSet<>();
        for(BA_Well well:all){
            String countryName = well.getCountry();//拿到国家(中国)数据
            WellBrowseOutDto country = dict.getOrDefault(countryName,new WellBrowseOutDto(countryName));//如果有key,就拿他的value，如果没有，就返回实体，实体是以国家作为label
            dict.put(countryName,country);

            String areaName = well.getArea();
            WellBrowseOutDto area = dict.getOrDefault(areaName,new WellBrowseOutDto(areaName));
            country.getChildren().add(area);
            dict.put(areaName,area);

            String blockName=well.getBlock();
            WellBrowseOutDto block=dict.getOrDefault(blockName,new WellBrowseOutDto(blockName));
            area.getChildren().add(block);
            dict.put(blockName,block);

            String oilfieldName=well.getOilField();
            WellBrowseOutDto oilfield=dict.getOrDefault(oilfieldName,new WellBrowseOutDto(oilfieldName));
            block.getChildren().add(oilfield);
            dict.put(oilfieldName,oilfield);

            String wellName=well.getWellName();
            WellBrowseOutDto single_well=dict.getOrDefault(wellName,new WellBrowseOutDto(wellName));
            oilfield.getChildren().add(single_well);
            dict.put(wellName,single_well);

            List<WellinfoDto> casingsizeAndIDs = cm_workBaseInfoRepository.findSizeAndId(countryName, areaName, blockName, oilfieldName, wellName);
            for(WellinfoDto casingsizeAndID:casingsizeAndIDs){
                single_well.getChildren().add(new WellBrowseOutDto(casingsizeAndID.getCasingSize(),casingsizeAndID.getCM_WorkBaseInfo_ID()));
            }

            result.add(country);
        }
        return R.ok().put("data",result);
    }

    // 11.16 到套管尺寸一级
    @Override
    public R getCompareTreeCasingSize(){
        // TODO: fix bug BA_WELL 与 CM_WORK_BASIC_INFO中的套管数据不同步
        // BA_Well
        // List<BA_Well> all = ba_wellRepository.findAll();

        // CM_WorkBaseInfo
        List<CM_WorkBaseInfo> all = cm_workBaseInfoRepository.findAll();
        Map<String,WellBrowseOutDto> dict=new HashMap<>();
        Set<WellBrowseOutDto> result = new HashSet<>();
        for(CM_WorkBaseInfo well:all){
            String countryName = well.getCountry();//拿到国家(中国)数据
            WellBrowseOutDto country = dict.getOrDefault(countryName,new WellBrowseOutDto(countryName));//如果有key,就拿他的value，如果没有，就返回实体，实体是以国家作为label
            dict.put(countryName,country);

            String areaName = well.getArea();
            WellBrowseOutDto area = dict.getOrDefault(areaName,new WellBrowseOutDto(areaName));
            country.getChildren().add(area);
            dict.put(areaName,area);

            String blockName=well.getBlock();
            WellBrowseOutDto block=dict.getOrDefault(blockName,new WellBrowseOutDto(blockName));
            area.getChildren().add(block);
            dict.put(blockName,block);

            String oilfieldName=well.getOilField();
            WellBrowseOutDto oilfield=dict.getOrDefault(oilfieldName,new WellBrowseOutDto(oilfieldName));
            block.getChildren().add(oilfield);
            dict.put(oilfieldName,oilfield);

            String wellName=well.getWellName();
            WellBrowseOutDto single_well=dict.getOrDefault(wellName,new WellBrowseOutDto(wellName));
            oilfield.getChildren().add(single_well);
            dict.put(wellName,single_well);

            // 井名下面显示出其包含的套管尺寸：casingSize
            String casingSize = well.getCasingSize();
            WellBrowseOutDto singleCasingSize=dict.getOrDefault(casingSize,new WellBrowseOutDto(casingSize));
            single_well.getChildren().add(singleCasingSize);
            dict.put(casingSize,singleCasingSize);

            result.add(country);
        }
        return R.ok().put("data",result);
    }

    @Override
    public R wellInfoDetail(String cm_WorkBaseInfo_ID) {
        CM_WorkBaseInfo well = cm_workBaseInfoRepository.findwellInfoDetailById(cm_WorkBaseInfo_ID);
        List<String> rowName=new LinkedList<>();
        List<String> wellBasicInfo=new LinkedList<>();
        rowName.add("井眼直径（in）");
        rowName.add("实际井深（m）");
        rowName.add("套管外径（in）");
        rowName.add("套管实际下深（m）");
        rowName.add("设计水泥浆返高（m）");
        rowName.add("管内水泥塞长度（m）");
        rowName.add("设计裸眼附加量（％）");
        rowName.add("实测水泥浆返高（m）");
        rowName.add("实探水泥塞顶深（m）");
        rowName.add("实际裸眼附加量（％）");
        rowName.add("固井方式：");
        rowName.add("泥浆性能：");
        rowName.add("泥浆类型");
        rowName.add("泥浆密度（g/cm3）");
        rowName.add("漏斗粘度（秒/夸脱）");
        rowName.add("屈服值PV（Pa或CP）");
        rowName.add("塑性粘度YP（mPa.s或lbs/100ft2）");
        rowName.add("切力（Pa或CP）");
        rowName.add("固井前循环参数：");
        rowName.add("循环排量（L/Min）");
        rowName.add("循环泵压（Psi）");
        rowName.add("裸眼环空返速（m/s）");
        wellBasicInfo.add(well.getHoleSize());
        wellBasicInfo.add(well.getHoleDepth());
        wellBasicInfo.add(well.getCasingSize());
        wellBasicInfo.add(well.getCasingBtmDepth());
        wellBasicInfo.add(well.getReturnDepth1());
        wellBasicInfo.add(well.getCementPlug());
        wellBasicInfo.add(well.getAdditiveVolume1());
        wellBasicInfo.add(well.getReturnDepth2());
        wellBasicInfo.add(well.getPlugTopDepth());
        wellBasicInfo.add(well.getAdditiveVolume2());
        wellBasicInfo.add(well.getCementType());
        wellBasicInfo.add(null);//泥浆性能
        wellBasicInfo.add(well.getMudType());
        wellBasicInfo.add(well.getMudDensity());
        wellBasicInfo.add(well.getFV());
        wellBasicInfo.add(well.getPV());
        wellBasicInfo.add(well.getYP());
        wellBasicInfo.add(well.getCP());
        wellBasicInfo.add(null);//固井前循环参数
        wellBasicInfo.add(well.getCycleDisplacement());
        wellBasicInfo.add(well.getCyclePump());
        wellBasicInfo.add(well.getAV());

        String table1Str="";
        table1Str+="[";
        for(int i=0;i<rowName.size();i++){
            if(wellBasicInfo.get(i)!=null){
                table1Str+="{";
                table1Str+="\"rowName\":" + "\"" + rowName.get(i) + "\",";
                table1Str+="\"rowData\":" + "\"" + wellBasicInfo.get(i) + "\"";
                table1Str+="},";
            }else{
                table1Str+="{";
                table1Str+="\"rowName\":" + "\"" + rowName.get(i) + "\",";
                table1Str+="\"rowData\":" + "\""  + "\"";
                table1Str+="},";
            }
        }
        table1Str+="]";
        JSONArray table1=JSONArray.fromObject(table1Str);

        //第二个table
        List<String> project=new LinkedList<>();
        List<String> firstMud=new LinkedList<>();
        List<String> midMud=new LinkedList<>();
        List<String> lastMud=new LinkedList<>();

        project.add("水泥浆类型");
        project.add("施工配方");
        project.add("试验温度BHST/BHCT(℃) ");
        project.add("密度(g/cm3)");
        project.add("造浆率(cuft/sk)");
        project.add("混合水率(gal/sk)");
        project.add("失水量(ml/7Mpa.30min)");
        project.add("自由水(％)");
        project.add("抗压强度(MPa/Psi)");
        project.add("可泵时间（hr:min）");
        project.add("稠化时间（hr:min）");

        firstMud.add(well.getSluryType1());
        firstMud.add(well.getFourmula1());
        firstMud.add(well.getBHSTCT1());
        firstMud.add(well.getSluryDensity1());
        firstMud.add(well.getPulpingRate1());
        firstMud.add(well.getMixedWaterRate1());
        firstMud.add(well.getLostWater1());
        firstMud.add(well.getFreeWater1());
        firstMud.add(well.getCompressiveStrength1());
        firstMud.add(well.getPumpTime1());
        firstMud.add(well.getThickeningTime1());

        midMud.add(well.getSluryType2());
        midMud.add(well.getFourmula2());
        midMud.add(well.getBHSTCT2());
        midMud.add(well.getSluryDensity2());
        midMud.add(well.getPulpingRate2());
        midMud.add(well.getMixedWaterRate2());
        midMud.add(well.getLostWater2());
        midMud.add(well.getFreeWater2());
        midMud.add(well.getCompressiveStrength2());
        midMud.add(well.getPumpTime2());
        midMud.add(well.getThickeningTime2());

        lastMud.add(well.getSluryType3());
        lastMud.add(well.getFourmula3());
        lastMud.add(well.getBHSTCT3());
        lastMud.add(well.getSluryDensity3());
        lastMud.add(well.getPulpingRate3());
        lastMud.add(well.getMixedWaterRate3());
        lastMud.add(well.getLostWater3());
        lastMud.add(well.getFreeWater3());
        lastMud.add(well.getCompressiveStrength3());
        lastMud.add(well.getPumpTime3());
        lastMud.add(well.getThickeningTime3());


        String table2Str="";
        table2Str+="[";
        for(int i=0;i<project.size();i++){
            if(firstMud.get(i)!=null&&midMud.get(i)!=null&&lastMud.get(i)!=null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table2Str+="},";
            }else if (firstMud.get(i)!=null&&midMud.get(i)!=null&&lastMud.get(i)==null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"lastMud\":" + "\"" + "\"";
                table2Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)!=null&&lastMud.get(i)!=null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\""  + "\",";
                table2Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table2Str+="},";
            }else if(firstMud.get(i)!=null&&midMud.get(i)==null&&lastMud.get(i)!=null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"midMud\":" + "\""  + "\",";
                table2Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table2Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)==null&&lastMud.get(i)!=null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\""  + "\",";
                table2Str+="\"midMud\":" + "\""  + "\",";
                table2Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table2Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)!=null&&lastMud.get(i)==null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\""  + "\",";
                table2Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"lastMud\":" + "\"" + "\"";
                table2Str+="},";
            }else if(firstMud.get(i)!=null&&midMud.get(i)==null&&lastMud.get(i)==null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table2Str+="\"midMud\":" + "\""  + "\",";
                table2Str+="\"lastMud\":" + "\"" + "\"";
                table2Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)==null&&lastMud.get(i)==null){
                table2Str+="{";
                table2Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table2Str+="\"firstMud\":" + "\"" +  "\",";
                table2Str+="\"midMud\":" + "\""  + "\",";
                table2Str+="\"lastMud\":" + "\"" +  "\"";
                table2Str+="},";
            }
        }
        table2Str+="]";
        JSONArray table2=JSONArray.fromObject(table2Str);

        //第三个table
        project=new LinkedList<>();
        firstMud=new LinkedList<>();
        midMud=new LinkedList<>();
        lastMud=new LinkedList<>();
        project.add("水泥浆体积(bbls)");
        project.add("干水泥用量(ton)");
        project.add("混合水用量(bbls)");
        project.add("水泥浆最高密度(g/cm3)");
        project.add("水泥浆最低密度(g/cm3)");
        project.add("水泥浆平均密度（g/cm3）");
        project.add("替浆量(bbl)");
        project.add("替浆速度(bbl/min)");
        project.add("碰压前最高顶替压力(MPa/Psi)");
        project.add("施工总耗时（管线试压开始至查回流结束）(min)");
        project.add("施工人员");
        project.add("施工日期");

        firstMud.add(well.getSluryVol1());
        firstMud.add(well.getDryCementVol1());
        firstMud.add(well.getMixWaterVol1());
        firstMud.add(well.getSluryMaxDensity1());
        firstMud.add(well.getSluryMinDensity1());
        firstMud.add(well.getSluryAvgDensity1());
        firstMud.add(well.getReplaceVol1());
        firstMud.add(well.getReplaceSpeed1());
        firstMud.add(well.getMaxDisplacement1());
        firstMud.add(well.getWorkTime1());
        firstMud.add(well.getWorkMan1());
        firstMud.add(well.getWorkDate1());

        midMud.add(well.getSluryVol2());
        midMud.add(well.getDryCementVol2());
        midMud.add(well.getMixWaterVol2());
        midMud.add(well.getSluryMaxDensity2());
        midMud.add(well.getSluryMinDensity2());
        midMud.add(well.getSluryAvgDensity2());
        midMud.add(well.getReplaceVol2());
        midMud.add(well.getReplaceSpeed2());
        midMud.add(well.getMaxDisplacement2());
        midMud.add(well.getWorkTime2());
        midMud.add(well.getWorkMan2());
        midMud.add(well.getWorkDate2());

        lastMud.add(well.getSluryVol3());
        lastMud.add(well.getDryCementVol3());
        lastMud.add(well.getMixWaterVol3());
        lastMud.add(well.getSluryMaxDensity3());
        lastMud.add(well.getSluryMinDensity3());
        lastMud.add(well.getSluryAvgDensity3());
        lastMud.add(well.getReplaceVol3());
        lastMud.add(well.getReplaceSpeed3());
        lastMud.add(well.getMaxDisplacement3());
        lastMud.add(well.getWorkTime3());
        lastMud.add(well.getWorkMan3());
        lastMud.add(well.getWorkDate3());

        String table3Str="";
        table3Str+="[";
        for(int i=0;i<project.size();i++){
            if(firstMud.get(i)!=null&&midMud.get(i)!=null&&lastMud.get(i)!=null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table3Str+="},";
            }else if (firstMud.get(i)!=null&&midMud.get(i)!=null&&lastMud.get(i)==null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"lastMud\":" + "\"" + "\"";
                table3Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)!=null&&lastMud.get(i)!=null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\""  + "\",";
                table3Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table3Str+="},";
            }else if(firstMud.get(i)!=null&&midMud.get(i)==null&&lastMud.get(i)!=null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"midMud\":" + "\""  + "\",";
                table3Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table3Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)==null&&lastMud.get(i)!=null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\""  + "\",";
                table3Str+="\"midMud\":" + "\""  + "\",";
                table3Str+="\"lastMud\":" + "\"" + lastMud.get(i).replace("\"","'") + "\"";
                table3Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)!=null&&lastMud.get(i)==null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\""  + "\",";
                table3Str+="\"midMud\":" + "\"" + midMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"lastMud\":" + "\"" + "\"";
                table3Str+="},";
            }else if(firstMud.get(i)!=null&&midMud.get(i)==null&&lastMud.get(i)==null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\"" + firstMud.get(i).replace("\"","'") + "\",";
                table3Str+="\"midMud\":" + "\""  + "\",";
                table3Str+="\"lastMud\":" + "\"" + "\"";
                table3Str+="},";
            }else if(firstMud.get(i)==null&&midMud.get(i)==null&&lastMud.get(i)==null){
                table3Str+="{";
                table3Str+="\"project\":" + "\"" + project.get(i) + "\",";
                table3Str+="\"firstMud\":" + "\"" +  "\",";
                table3Str+="\"midMud\":" + "\""  + "\",";
                table3Str+="\"lastMud\":" + "\"" +  "\"";
                table3Str+="},";
            }
        }
        table3Str+="]";
        JSONArray table3=JSONArray.fromObject(table3Str);

        //第四个table
        List<String> fluid=new LinkedList<>();
        List<String> composition=new LinkedList<>();
        List<String> density=new LinkedList<>();
        List<String> Vol=new LinkedList<>();
        fluid.add("清洗液");
        fluid.add("隔离液");
        composition.add(well.getCleaningFluidFormula());
        composition.add(well.getSpacerFluidFormula());
        density.add(well.getCleaningFluidDensity());
        density.add(well.getSpacerFluidDensity());
        Vol.add(well.getCleaningFluidVol());
        Vol.add(well.getSpacerFluidVol());
        String table4Str="";
        table4Str+="[";
        for(int i=0;i<fluid.size();i++){
            if(composition.get(i)!=null)
            {
                table4Str+="{";
                table4Str+="\"fluid\":" + "\"" + fluid.get(i) + "\",";
                table4Str+="\"composition\":" + "\"" + composition.get(i) + "\",";
                table4Str+="\"density\":" + "\"" + density.get(i) + "\",";
                table4Str+="\"Vol\":" + "\"" + Vol.get(i) + "\"";
                table4Str+="},";
            }
        }
        table4Str+="]";
        JSONArray table4=JSONArray.fromObject(table4Str);

        return R.ok().put("table1",table1).put("table2",table2).put("table3",table3).put("table4",table4);
    }


    @Override
    public R getTreeByCompany(String company) {
        try {
            company=URLDecoder.decode(company,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        List<BA_Well> all = ba_wellRepository.findAllByCementCompany(company);
        Map<String,WellBrowseOutDto> dict=new HashMap<>();
        Set<WellBrowseOutDto> result = new HashSet<>();
        for(BA_Well well:all) {
            String countryName = well.getCountry();//拿到国家(中国)数据
            WellBrowseOutDto country = dict.getOrDefault(countryName, new WellBrowseOutDto(countryName));//如果有key,就拿他的value，如果没有，就返回实体，实体是以国家作为label
            dict.put(countryName, country);

            String areaName = well.getArea();
            WellBrowseOutDto area = dict.getOrDefault(areaName, new WellBrowseOutDto(areaName));
            country.getChildren().add(area);
            dict.put(areaName, area);

            String blockName = well.getBlock();
            WellBrowseOutDto block = dict.getOrDefault(blockName, new WellBrowseOutDto(blockName));
            area.getChildren().add(block);
            dict.put(blockName, block);

            String oilfieldName = well.getOilField();
            WellBrowseOutDto oilfield = dict.getOrDefault(oilfieldName, new WellBrowseOutDto(oilfieldName));
            block.getChildren().add(oilfield);
            dict.put(oilfieldName, oilfield);

            String wellName = well.getWellName();
            WellBrowseOutDto single_well = dict.getOrDefault(wellName, new WellBrowseOutDto(wellName));
            oilfield.getChildren().add(single_well);

            result.add(country);
        }

        return R.ok().put("data",result).put("company",company);
    }

    @Override
    public R upload(MultipartFile[] multipartFiles,String wellName) {
        try {
            wellName=URLDecoder.decode(wellName,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        wellName=wellName.replaceAll("xiegang","//");

        //在文件操作中，不用/或者\最好，推荐使用File.separator
        String rootPath="C:"+File.separator+"WellDoc"+File.separator+wellName+File.separator;
        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        try {
            if (multipartFiles != null && multipartFiles.length > 0) {
                for(int i = 0;i<multipartFiles.length;i++){

                    //以原来的名称命名,覆盖掉旧的
                    String storagePath = rootPath+multipartFiles[i].getOriginalFilename();
                    //下面代码是控制台打印文件路径
                    Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
                    String suffix=multipartFiles[i].getOriginalFilename().split("\\.")[multipartFiles[i].getOriginalFilename().split("\\.").length-1];
                    if(suffix.equals("zip")){
                        //解压前的文件
                        File zipFile=new File(storagePath);
                        //解压后的文件位置为rooPath
                        //rooPath在调用解压方法时加上解压包的名
                        UnZipUtil.unZip(zipFile, rootPath);
                        //删除zip文件
                        FileUtil fileUtil=new FileUtil();
                        fileUtil.deleteFile(storagePath);
                    }else if(suffix.equals("rar")){
                        String fileName=multipartFiles[i].getOriginalFilename().replace(".rar","");
                        //rar和zip方法参数有点区别，具体阅读UnZipUtil
                        UnZipUtil.unRar(storagePath, rootPath+fileName);
                        //删除zip文件
                        FileUtil fileUtil=new FileUtil();
                        fileUtil.deleteFile(storagePath);
                    }

                }
            }

        } catch (Exception e) {
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R wellDocTree(String company) {
        try {
            company = URLDecoder.decode(company, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        List<BA_Well> all = ba_wellRepository.findAllByCementCompany(company);
        Map<String,WellBrowseOutDto> dict=new HashMap<>();
        Set<WellBrowseOutDto> result = new HashSet<>();
        for(BA_Well well:all){
            String countryName = well.getCountry();//拿到国家(中国)数据
            WellBrowseOutDto country = dict.getOrDefault(countryName,new WellBrowseOutDto(countryName));//如果有key,就拿他的value，如果没有，就返回实体，实体是以国家作为label
            dict.put(countryName,country);

            String areaName = well.getArea();
            WellBrowseOutDto area = dict.getOrDefault(areaName,new WellBrowseOutDto(areaName));
            country.getChildren().add(area);
            dict.put(areaName,area);

            String blockName=well.getBlock();
            WellBrowseOutDto block=dict.getOrDefault(blockName,new WellBrowseOutDto(blockName));
            area.getChildren().add(block);
            dict.put(blockName,block);

            String oilfieldName=well.getOilField();
            WellBrowseOutDto oilfield=dict.getOrDefault(oilfieldName,new WellBrowseOutDto(oilfieldName));
            block.getChildren().add(oilfield);
            dict.put(oilfieldName,oilfield);

            String wellName=well.getWellName();
            WellBrowseOutDto single_well=dict.getOrDefault(wellName,new WellBrowseOutDto(wellName));
            oilfield.getChildren().add(single_well);

            result.add(country);
        }
        return R.ok().put("data", result).put("company", company);
    }

    @Override
    public R createNewFile(String fileName) {
        try {
            fileName=URLDecoder.decode(fileName,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        fileName=fileName.replaceAll("xiegang","//");

        String rootPath="C:"+File.separator+"WellDoc"+File.separator+fileName+File.separator;
        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        return R.ok();
    }

    @Override
    public R deleteFile(String filePath) {
        String path=doc_root+filePath;
        System.out.println(path);
        File file=new File(path);
        if(file.exists()){
            FileUtil.deleteDir(path);
            return R.ok("文件删除成功");
        }else {
            return R.error("文件不存在");
        }
    }

    @Override
    public R loginCompany(HttpServletRequest request) {
        //获取当前登陆人的公司
        String token=request.getHeader("Authorization");
        SysUser user = sysUserRepository.findByToken(token);
        String loginUser_company=user.getCompany().getNAME();
        List<String> list_company=sysm_companyRepository.findName();
        //构造所有公司json
        String data2="";
        data2+="[";
        for(String company:list_company){
            data2+="{";
            data2+="\"company\":" + "\"" + company + "\"";
            data2+="},";
        }
        data2+="]";
        JSONArray data2Json=JSONArray.fromObject(data2);
        return R.ok().put("data2",data2Json).put("data3",loginUser_company);
    }

    @Override
    public R wellBrowse(HttpServletRequest request) {
        //获取当前登陆人的公司
        String token=request.getHeader("Authorization");
        SysUser user = sysUserRepository.findByToken(token);
        String loginUser_company=user.getCompany().getNAME();
        List<String> list_company=sysm_companyRepository.findName();
        //构造所有公司json
        String data2="";
        data2+="[";
        for(String company:list_company){
            data2+="{";
            data2+="\"company\":" + "\"" + company + "\"";
            data2+="},";
        }
        data2+="]";
        JSONArray data2Json=JSONArray.fromObject(data2);

        List<BA_Well> all = ba_wellRepository.findAllByCementCompany(loginUser_company);
        Map<String,WellBrowseOutDto> dict=new HashMap<>();
        Set<WellBrowseOutDto> result = new HashSet<>();
        for(BA_Well well:all){
            String countryName = well.getCountry();//拿到国家(中国)数据
            WellBrowseOutDto country = dict.getOrDefault(countryName,new WellBrowseOutDto(countryName));//如果有key,就拿他的value，如果没有，就返回实体，实体是以国家作为label
            dict.put(countryName,country);

            String areaName = well.getArea();
            WellBrowseOutDto area = dict.getOrDefault(areaName,new WellBrowseOutDto(areaName));
            country.getChildren().add(area);
            dict.put(areaName,area);

            String blockName=well.getBlock();
            WellBrowseOutDto block=dict.getOrDefault(blockName,new WellBrowseOutDto(blockName));
            area.getChildren().add(block);
            dict.put(blockName,block);

            String oilfieldName=well.getOilField();
            WellBrowseOutDto oilfield=dict.getOrDefault(oilfieldName,new WellBrowseOutDto(oilfieldName));
            block.getChildren().add(oilfield);
            dict.put(oilfieldName,oilfield);

            String wellName=well.getWellName();
            WellBrowseOutDto single_well=dict.getOrDefault(wellName,new WellBrowseOutDto(wellName));
            oilfield.getChildren().add(single_well);
            dict.put(wellName,single_well);

            List<WellinfoDto> casingsizeAndIDs = cm_workBaseInfoRepository.findCasingsizeAndID(loginUser_company, countryName, areaName, blockName, oilfieldName, wellName);
            for(WellinfoDto casingsizeAndID:casingsizeAndIDs){
                single_well.getChildren().add(new WellBrowseOutDto(casingsizeAndID.getCasingSize(),casingsizeAndID.getCM_WorkBaseInfo_ID()));
            }

            result.add(country);

        }
        // System.out.println(dict);
        return R.ok().put("data",result).put("data2",data2Json).put("data3",loginUser_company);
    }

    @Override
    public R execQuery(SqlDto sqlDto) throws Exception {
        JSONObject rs = dbHelper.execQuery(sqlDto.getSql());
        return R.ok().putData(rs);
    }

    @Override
    public R execUpdate(SqlDto sqlDto) throws Exception {
        int count = dbHelper.execUpdate(sqlDto.getSql());
        return R.ok().putData(count);
    }
}
